import React, { createContext, useContext, useReducer, useEffect } from 'react';

// 数据状态管理
const DataContext = createContext();

// 数据动作类型
const DATA_ACTIONS = {
  SET_MODULE_DATA: 'SET_MODULE_DATA',
  UPDATE_MODULE_DATA: 'UPDATE_MODULE_DATA',
  SYNC_CROSS_MODULE: 'SYNC_CROSS_MODULE',
  SET_GLOBAL_FILTERS: 'SET_GLOBAL_FILTERS',
  SET_USER_PREFERENCES: 'SET_USER_PREFERENCES',
  ADD_NOTIFICATION: 'ADD_NOTIFICATION',
  REMOVE_NOTIFICATION: 'REMOVE_NOTIFICATION'
};

// 初始数据状态
const initialState = {
  // 各模块数据
  modules: {
    carbon: {
      emissions: {
        scope1: 12580,
        scope2: 8960,
        scope3: 34200,
        total: 55740,
        intensity: 0.85,
        trend: -12 // 百分比变化
      },
      targets: {
        reduction2030: 30,
        current: 15,
        timeline: '2030-12-31'
      },
      suppliers: {
        assessed: 76,
        total: 100,
        highRisk: 5,
        improved: 12
      }
    },
    compliance: {
      score: 94.2,
      audits: {
        completed: 8,
        scheduled: 3,
        overdue: 1
      },
      regulations: {
        total: 45,
        compliant: 42,
        pending: 3
      }
    },
    workbench: {
      projects: {
        total: 15,
        active: 8,
        completed: 5,
        delayed: 2
      },
      team: {
        members: 12,
        online: 9,
        tasks: 34
      }
    },
    reporting: {
      reports: {
        annual: { status: 'in-progress', progress: 89, deadline: '2024-03-31' },
        quarterly: { status: 'completed', progress: 100, deadline: '2024-01-31' },
        monthly: { status: 'active', progress: 45, deadline: '2024-02-15' }
      },
      disclosure: {
        platforms: ['CDP', 'GRI', 'TCFD'],
        submitted: 2,
        pending: 1
      }
    },
    'supply-chain': {
      suppliers: {
        total: 156,
        assessed: 118,
        certified: 89,
        improvement: 23
      },
      risks: {
        high: 8,
        medium: 25,
        low: 85
      }
    }
  },
  
  // 全局筛选器
  globalFilters: {
    timeRange: 'current-year',
    region: 'all',
    businessUnit: 'all'
  },
  
  // 用户偏好设置
  userPreferences: {
    theme: 'light',
    language: 'zh-CN',
    notifications: true,
    dashboardLayout: 'grid'
  },
  
  // 通知系统
  notifications: [],
  
  // 跨模块业务流程状态
  workflows: {
    'annual-report': {
      status: 'in-progress',
      progress: 65,
      involvedModules: ['carbon', 'compliance', 'supply-chain', 'reporting'],
      currentStep: 'compliance-review',
      nextActions: [
        { module: 'compliance', action: '完成合规审核', assignee: '张合规' },
        { module: 'reporting', action: '更新报告模板', assignee: '李报告' }
      ]
    },
    'carbon-reduction': {
      status: 'planning',
      progress: 25,
      involvedModules: ['carbon', 'supply-chain', 'compliance'],
      currentStep: 'target-setting',
      nextActions: [
        { module: 'carbon', action: '设定2025年减排目标', assignee: '王碳排' },
        { module: 'supply-chain', action: '制定供应商减排要求', assignee: '赵供应' }
      ]
    }
  }
};

// 数据状态归并器
const dataReducer = (state, action) => {
  switch (action.type) {
    case DATA_ACTIONS.SET_MODULE_DATA:
      return {
        ...state,
        modules: {
          ...state.modules,
          [action.module]: {
            ...state.modules[action.module],
            ...action.data
          }
        }
      };
    
    case DATA_ACTIONS.UPDATE_MODULE_DATA:
      return {
        ...state,
        modules: {
          ...state.modules,
          [action.module]: {
            ...state.modules[action.module],
            [action.field]: action.value
          }
        }
      };
    
    case DATA_ACTIONS.SYNC_CROSS_MODULE:
      // 处理跨模块数据同步
      const updatedState = { ...state };
      if (action.sourceModule === 'carbon' && action.field === 'emissions') {
        // 碳排放数据更新时，同步到报告模块
        updatedState.modules.reporting.carbonData = action.value;
      }
      return updatedState;
    
    case DATA_ACTIONS.SET_GLOBAL_FILTERS:
      return {
        ...state,
        globalFilters: {
          ...state.globalFilters,
          ...action.filters
        }
      };
    
    case DATA_ACTIONS.SET_USER_PREFERENCES:
      return {
        ...state,
        userPreferences: {
          ...state.userPreferences,
          ...action.preferences
        }
      };
    
    case DATA_ACTIONS.ADD_NOTIFICATION:
      return {
        ...state,
        notifications: [
          ...state.notifications,
          {
            id: Date.now(),
            timestamp: new Date().toISOString(),
            ...action.notification
          }
        ]
      };
    
    case DATA_ACTIONS.REMOVE_NOTIFICATION:
      return {
        ...state,
        notifications: state.notifications.filter(n => n.id !== action.id)
      };
    
    default:
      return state;
  }
};

// 数据提供者组件
export const DataProvider = ({ children }) => {
  const [state, dispatch] = useReducer(dataReducer, initialState);
  
  // 数据操作方法
  const setModuleData = (module, data) => {
    dispatch({ type: DATA_ACTIONS.SET_MODULE_DATA, module, data });
  };
  
  const updateModuleData = (module, field, value) => {
    dispatch({ type: DATA_ACTIONS.UPDATE_MODULE_DATA, module, field, value });
    // 触发跨模块同步
    dispatch({ type: DATA_ACTIONS.SYNC_CROSS_MODULE, sourceModule: module, field, value });
  };
  
  const setGlobalFilters = (filters) => {
    dispatch({ type: DATA_ACTIONS.SET_GLOBAL_FILTERS, filters });
  };
  
  const setUserPreferences = (preferences) => {
    dispatch({ type: DATA_ACTIONS.SET_USER_PREFERENCES, preferences });
  };
  
  const addNotification = (notification) => {
    dispatch({ type: DATA_ACTIONS.ADD_NOTIFICATION, notification });
  };
  
  const removeNotification = (id) => {
    dispatch({ type: DATA_ACTIONS.REMOVE_NOTIFICATION, id });
  };
  
  // 获取模块数据
  const getModuleData = (module) => {
    return state.modules[module] || {};
  };
  
  // 获取跨模块聚合数据
  const getAggregatedData = () => {
    const carbon = state.modules.carbon;
    const compliance = state.modules.compliance;
    const supplyChain = state.modules['supply-chain'];
    const reporting = state.modules.reporting;
    
    return {
      esg_score: {
        overall: ((carbon.intensity < 1.0 ? 85 : 75) + compliance.score + 
                 (supplyChain.suppliers.certified / supplyChain.suppliers.total * 100)) / 3,
        carbon: carbon.intensity < 1.0 ? 85 : 75,
        governance: compliance.score,
        social: supplyChain.suppliers.certified / supplyChain.suppliers.total * 100
      },
      key_metrics: {
        carbon_intensity: carbon.emissions.intensity,
        compliance_score: compliance.score,
        supplier_assessment: supplyChain.suppliers.assessed / supplyChain.suppliers.total * 100,
        report_completion: reporting.reports.annual.progress
      }
    };
  };
  
  // 获取待处理任务
  const getPendingTasks = () => {
    const tasks = [];
    
    // 从各模块收集待处理任务
    Object.values(state.workflows).forEach(workflow => {
      workflow.nextActions.forEach(action => {
        tasks.push({
          id: `${workflow.status}-${action.module}-${Date.now()}`,
          title: action.action,
          module: action.module,
          assignee: action.assignee,
          workflow: workflow.status,
          priority: workflow.status === 'in-progress' ? 'high' : 'medium'
        });
      });
    });
    
    return tasks;
  };
  
  const value = {
    state,
    setModuleData,
    updateModuleData,
    setGlobalFilters,
    setUserPreferences,
    addNotification,
    removeNotification,
    getModuleData,
    getAggregatedData,
    getPendingTasks
  };
  
  return (
    <DataContext.Provider value={value}>
      {children}
    </DataContext.Provider>
  );
};

// 使用数据的Hook
export const useData = () => {
  const context = useContext(DataContext);
  if (!context) {
    throw new Error('useData must be used within a DataProvider');
  }
  return context;
};

// 专门用于模块数据的Hook
export const useModuleData = (moduleName) => {
  const { getModuleData, updateModuleData } = useData();
  
  const data = getModuleData(moduleName);
  
  const updateData = (field, value) => {
    updateModuleData(moduleName, field, value);
  };
  
  return { data, updateData };
};

// 全局筛选器Hook
export const useGlobalFilters = () => {
  const { state, setGlobalFilters } = useData();
  
  return {
    filters: state.globalFilters,
    setFilters: setGlobalFilters
  };
};

// 通知系统Hook
export const useNotifications = () => {
  const { state, addNotification, removeNotification } = useData();
  
  return {
    notifications: state.notifications,
    addNotification,
    removeNotification
  };
};

// 跨模块工作流Hook
export const useWorkflows = () => {
  const { state } = useData();
  
  const getWorkflowByModule = (moduleName) => {
    return Object.values(state.workflows).filter(workflow => 
      workflow.involvedModules.includes(moduleName)
    );
  };
  
  const getWorkflowById = (workflowId) => {
    return state.workflows[workflowId];
  };
  
  return {
    workflows: state.workflows,
    getWorkflowByModule,
    getWorkflowById
  };
};

// 数据同步效果
export const useDataSync = () => {
  const { state, updateModuleData } = useData();
  
  // 模拟数据同步机制
  const syncData = (sourceModule, targetModule, mapping) => {
    const sourceData = state.modules[sourceModule];
    const mappedData = {};
    
    Object.entries(mapping).forEach(([sourceField, targetField]) => {
      if (sourceData[sourceField] !== undefined) {
        mappedData[targetField] = sourceData[sourceField];
      }
    });
    
    Object.entries(mappedData).forEach(([field, value]) => {
      updateModuleData(targetModule, field, value);
    });
  };
  
  return { syncData };
}; 